<template>
    <div class="test-page">
        <div class="test-container">
            <h2>流式请求测试</h2>

            <!-- 结果显示区域 -->
            <div class="result-section">
                <el-input type="textarea" v-model="resultText" placeholder="流式结果将在这里显示..." :rows="15" readonly
                    class="result-textarea" />
            </div>

            <!-- 操作按钮 -->
            <div class="button-section">
                <el-button type="primary" @click="handleSendClick" :loading="isLoading" class="send-btn">
                    {{ isLoading ? "请求中..." : "开始流式请求" }}
                </el-button>
                <el-button @click="clearResult" :disabled="!resultText" class="clear-btn">
                    清空结果
                </el-button>
            </div>

            <!-- 状态信息 -->
            <div class="status-section" v-if="statusText">
                <el-alert :title="statusText" :type="statusType" :closable="false" show-icon />
            </div>
        </div>
    </div>
</template>

<script>
import { fetchEventSource } from '@microsoft/fetch-event-source';

export default {
    name: "Test",
    data() {
        return {
            resultText: "",
            isLoading: false,
            statusText: "",
            statusType: "info",
        };
    },
    methods: {
        // 处理发送按钮点击事件
        handleSendClick() {
            console.log("发送按钮被点击");

            // 直接执行GET请求，不需要检查输入内容
            this.sendStreamRequest();
        },

        async sendStreamRequest() {
            console.log("开始发送流式请求");
            this.isLoading = true;
            this.resultText = "";
            this.statusText = "正在建立连接...";
            this.statusType = "info";

            try {
                await this.streamRequest();
            } catch (error) {
                console.error("流式请求错误:", error);
                this.statusText = "请求失败: " + error.message;
                this.statusType = "error";

                // 显示更详细的错误信息
                this.$message({
                    message: "请求失败: " + error.message,
                    type: "error",
                    duration: 5000,
                    showClose: true,
                });

                // 在结果区域也显示错误信息
                this.resultText = `错误信息：\n${error.message
                    }\n\n调试信息：\n- 请求URL: /api/flux/test\n- 请求时间: ${new Date().toLocaleString()}\n- 请求方式: GET`;
            } finally {
                this.isLoading = false;
                console.log("流式请求结束");
            }
        },

        async streamRequest() {
            const self = this;
            // 建立连接
            await fetchEventSource('/api/sample/flux', {
                method: 'GET',
                headers: {
                    'Accept': 'text/event-stream',
                    'Cache-Control': 'no-cache',
                    'Connection': 'keep-alive'
                    // 可以添加其他请求头，如认证信息
                },
                onmessage(event) {
                    // 处理接收到的消息
                    console.log(event.data);
                    self.resultText += event.data + '\n';
                    self.scrollToBottom();
                },
                onopen(response) {
                    // 连接打开时的回调
                    console.log('Connection opened:', response.status);
                },
                onerror(error) {
                    // 错误处理
                    console.error('Error:', error);
                },
                onclose() {
                    // 连接关闭时的回调
                    console.log('Connection closed');
                }
            });
        },

        async streamRequest1() {
    const self = this;
    
    // 如果已存在连接，先关闭
    if (this.eventSource) {
        this.eventSource.close();
        this.eventSource = null;
    }
    
    try {
        // 使用正确的URL
        const eventSource = new EventSource('/api/sample/see');
        
        eventSource.addEventListener('message', function (event) {
            console.log('Received:', event.data);
            try {
                const data = JSON.parse(event.data);
                self.resultText += data.data + '\n';
                self.scrollToBottom();
            } catch (e) {
                console.error('Parse error:', e);
            }
        });
        
        eventSource.addEventListener('open', function (event) {
            console.log('Connection opened');
        });
        
        eventSource.addEventListener('error', function (event) {
            console.error('EventSource error:', event);
            // 检查连接状态
            if (eventSource.readyState === EventSource.CLOSED) {
                console.log('Connection was closed');
            }
        });
        
        // 添加自定义事件监听（如果需要）
        eventSource.addEventListener('custom-event', function (event) {
            console.log('Custom event:', event.data);
        });
        
        // 保存引用以便后续关闭
        this.eventSource = eventSource;
        
    } catch (error) {
        console.error('Failed to create EventSource:', error);
    }
},

// 添加关闭连接的方法
closeConnection() {
    if (this.eventSource) {
        this.eventSource.close();
        this.eventSource = null;
        console.log('Connection closed');
    }
},

        async realStreamRequest() {
            console.log("发送GET流式请求到:");

            this.statusText = `正在连接服务器...`;
            this.statusType = "info";

            try {
                const response = await fetch("/api/sample/see", {
                    method: "GET",
                });

                console.log("响应状态:", response.status, response.statusText);

                if (!response.ok) {
                    const errorText = await response.text();
                    console.error("服务器错误响应:", errorText);
                    throw new Error(
                        `服务器响应错误: ${response.status} ${response.statusText}\n详情: ${errorText}`
                    );
                }

                if (!response.body) {
                    throw new Error("响应体为空，服务器可能不支持流式传输");
                }

                this.statusText = "正在接收数据...";
                this.statusType = "success";

                const reader = response.body.getReader();
                const decoder = new TextDecoder("utf-8");

                try {
                    while (true) {
                        const { done, value } = await reader.read();

                        if (done) {
                            console.log("流式传输完成");
                            break;
                        }

                        // 解码数据块
                        const chunk = decoder.decode(value, { stream: true });
                        console.log("接收到数据块:", chunk);

                        // 直接显示数据块
                        this.resultText += chunk;

                        // 滚动到底部
                        this.$nextTick(() => {
                            this.scrollToBottom();
                        });
                    }

                    this.statusText = "请求完成！";
                    this.statusType = "success";

                    // 5秒后清除状态信息
                    setTimeout(() => {
                        this.statusText = "";
                    }, 5000);
                } finally {
                    reader.releaseLock();
                }
            } catch (networkError) {
                console.error("网络请求失败:", networkError);

                // 检查是否是网络连接问题
                if (
                    networkError.name === "TypeError" &&
                    networkError.message.includes("fetch")
                ) {
                    throw new Error(
                        `无法连接到服务器 ${streamUrl}\n请检查：\n1. 后端服务是否启动\n2. 端口是否正确\n3. 是否存在跨域问题`
                    );
                }

                throw networkError;
            }
        },

        async connectWithFetch() {
            const response = await fetch("/api/sample/see", {
                method: "GET",
                headers: { "Content-Type": "application/json" }
            });

            const reader = response.body.getReader();
            const decoder = new TextDecoder();

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                // 解码并处理数据块
                const chunk = decoder.decode(value, { stream: true });
                // 直接显示数据块
                this.resultText += chunk;
                console.log("Received chunk:", chunk);

                // 滚动到底部
                this.$nextTick(() => {
                    this.scrollToBottom();
                });
            }
        },

        scrollToBottom() {
            // 自动滚动到底部
            this.$nextTick(() => {
                const textarea = this.$el.querySelector(".result-textarea textarea");
                if (textarea) {
                    textarea.scrollTop = textarea.scrollHeight;
                }
            });
        },

        clearResult() {
            console.log("清空结果按钮被点击");
            this.resultText = "";
            this.statusText = "";
            this.$message.success("结果已清空");
        },
    },

    // 组件挂载后的调试信息
    mounted() {
        console.log("TestPage 组件已挂载");
        console.log("Element UI 是否可用:", !!this.$message);

        // 测试消息组件
        setTimeout(() => {
            console.log("测试消息提示功能");
        }, 1000);
    },
};
</script>

<style scoped>
.test-page {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    position: relative;
    z-index: 1;
}

.test-container {
    background: rgba(18, 18, 38, 0.8);
    border-radius: 15px;
    padding: 30px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
}

h2 {
    text-align: center;
    color: #fff;
    margin-bottom: 30px;
    font-size: 24px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.input-section {
    margin-bottom: 20px;
}

.input-field {
    width: 100%;
}

.input-field>>>.el-input__inner {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #fff;
    border-radius: 8px;
    padding: 12px 15px;
    font-size: 14px;
}

.input-field>>>.el-input__inner::placeholder {
    color: rgba(255, 255, 255, 0.5);
}

.input-field>>>.el-input__inner:focus {
    border-color: #4fc3f7;
    box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.2);
}

.result-section {
    margin-bottom: 20px;
}

.result-textarea {
    width: 100%;
}

.result-textarea>>>.el-textarea__inner {
    background: rgba(0, 0, 0, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #fff;
    border-radius: 8px;
    padding: 15px;
    font-size: 14px;
    line-height: 1.6;
    font-family: "Consolas", "Monaco", "Courier New", monospace;
    resize: vertical;
    min-height: 300px;
}

.result-textarea>>>.el-textarea__inner::placeholder {
    color: rgba(255, 255, 255, 0.5);
}

.result-textarea>>>.el-textarea__inner:focus {
    border-color: #4fc3f7;
    box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.2);
}

.button-section {
    display: flex;
    gap: 15px;
    justify-content: center;
    margin-bottom: 20px;
}

.send-btn {
    background: linear-gradient(45deg, #4fc3f7, #2196f3);
    border: none;
    padding: 12px 30px;
    font-size: 16px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.send-btn:hover:not(:disabled) {
    background: linear-gradient(45deg, #2196f3, #4fc3f7);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(79, 195, 247, 0.3);
}

.clear-btn {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #fff;
    padding: 12px 30px;
    font-size: 16px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.clear-btn:hover:not(:disabled) {
    background: rgba(255, 255, 255, 0.2);
    transform: translateY(-2px);
}

.status-section {
    margin-top: 20px;
}

.status-section>>>.el-alert {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 8px;
}

.status-section>>>.el-alert__title {
    color: #fff;
}

.status-section>>>.el-alert__icon {
    color: #4fc3f7;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.test-container {
    animation: fadeIn 0.5s ease-out;
}

@media (max-width: 768px) {
    .test-page {
        padding: 10px;
    }

    .test-container {
        padding: 20px;
    }

    .button-section {
        flex-direction: column;
        align-items: center;
    }

    .send-btn,
    .clear-btn {
        width: 100%;
        max-width: 200px;
    }
}
</style>
